package com.itheima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.utils.JwtUtils;
import com.itheima.common.utils.Md5Util;
import com.itheima.user.dto.LoginDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.service.ApUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author czh
 * @since 2021-08-20
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public String login(LoginDto dto) {
        String token = null;
        //游客登录
        if (dto.getFlag() == 0) {
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("flag",dto.getFlag());//0
            dataMap.put("equipmentId",dto.getEquipmentId());//机器号

            //生成令牌
             token = JwtUtils.token(dataMap);
            return token;
        }
        //会员登录
        //根据用户名获取用户信息

        QueryWrapper<ApUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",dto.getPhone());
        ApUser apUser = apUserMapper.selectOne(queryWrapper);
        //判断是否存在
        if (apUser != null){
            //得到盐
            String salt = apUser.getSalt();
            if (salt!=null){
                //密码加密进行校验
                String loginPassword = Md5Util.toMD5(dto.getPassword(), salt);
                if (loginPassword.equals(apUser.getPassword())){
                    apUser.setPassword("*");
                    Map<String,Object> map = new HashMap<>();
                    map.put("flag",dto.getFlag());
                    map.put("equipmentId",dto.getEquipmentId());
                    map.putAll(JSON.parseObject(JSON.toJSONString(apUser)));
                    //登陆成功
                     token = JwtUtils.token(map);

                }

            }


        }

        return token;
    }
}
